package org.ling.xuan.util;

import cn.hutool.core.collection.CollUtil;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class EmailUtil {
    public static void sendEmail(String host, String username, String password, int port, boolean ssl, String form, String title, String msg, List<String> reciver, List<String> copy, List<String> files) throws MessagingException, IOException {
        Session session = null;
        session = getSession(host, String.valueOf(port), ssl, username, password);
        Message message = new MimeMessage(session);
        Address[] addresses = new Address[reciver.size()];
        for (int i = 0; i < reciver.size(); i++) {
            addresses[i] = new InternetAddress(reciver.get(i));
        }
        message.addRecipients(Message.RecipientType.TO, addresses);
        Address[] cpa = new Address[copy.size()];
        for (int i = 0; i < copy.size(); i++) {
            cpa[i] = new InternetAddress(copy.get(i));
        }
        message.addRecipients(Message.RecipientType.CC, cpa);
        message.setFrom(new InternetAddress(form));


        message.setSubject(title);
        if (CollUtil.isEmpty(files)) {
            message.setText(msg);
        } else {
            Multipart multipart = new MimeMultipart();
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(msg);
            multipart.addBodyPart(textPart);
            for (String filePath : files) {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(filePath);
                multipart.addBodyPart(attachmentPart);
            }
            message.setContent(multipart);
        }
        Transport.send(message);
    }

    public static Session getSession(String host, String port, boolean ssl, String username, String password) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", String.valueOf(ssl)); // 启用SSL连接
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port); // 使用SSL的SMTP端口号

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        session.setDebug(false);
        return session;
    }
}
